package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice//标志为全局异常处理类
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)//拦截IllegalArgumentException异常
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e) {
        log.error("发生异常：{}", e.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
    }
    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        log.error("发生异常1：{}", e.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
    }
//    @ExceptionHandler(Throwable.class)
//    public JsonResult doHandleThrowable(Throwable e) {
//        log.error("发生异常：{}", e.getMessage());
//        return new JsonResult(StatusCode.THROWABLE_ERROR, e.getMessage());
//    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(": ")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        String data = "文件大小超出限制";
        log.error("MaxUploadSizeExceededException:" + data);
        return new JsonResult(StatusCode.FILE_UPLOAD_ERROR, data);
    }

}
